<template>
  <div>
    <div class="order-container">
      <!-- 填写订单信息区域 -->
      <div class="form-section">
        <h3 class="section-title">填写订单信息</h3>

        <!-- 收货人信息 -->
        <div class="info-group">
          <h4 class="group-title">收货人信息</h4>
          <div class="add-address">
            <a href="#" class="add-btn">
              <i class="icon-add"></i>新增收货地址
            </a>
          </div>

          <!-- 这里可以动态显示已保存的地址列表 -->
          <div class="address-list">
            <!-- 示例地址卡片 - 实际项目中可通过v-for循环生成 -->
            <div class="address-card selected">
              <div class="address-header">
                <!-- 绑定userInfo的name属性 -->
                <span class="name">{{ userInfo.data.username }}</span>
                <!-- 绑定userInfo的phone属性 -->
                <span class="phone">{{ userInfo.data.phone }}</span>
                <span class="default-tag">默认</span>
              </div>
              <!-- 绑定userInfo的address属性 -->
              <div class="address-detail">{{ userInfo.data.address }}</div>
              <div class="address-actions">
                <a href="#" class="edit">编辑</a>
                <a href="#" class="delete">删除</a>
              </div>
            </div>
          </div>


        </div>

        <!-- 订购人信息 -->
        <div class="info-group">
          <h4 class="group-title">订购人信息</h4>
          <div class="form-row">
            <div class="form-item">
              <label class="label">
                <span class="required">*</span>姓名:
              </label>
              <span class="input">{{ userInfo.data.username }}</span>
              <!-- <input type="text" class="input" placeholder="订购人名称" value="{{ userInfo.data.username }}"> -->
            </div>
            <div class="form-item">
              <label class="label">
                <span class="required">*</span>电话:
              </label>
              <span class="input">{{ userInfo.data.phone }}</span>
              <!-- <input type="text" class="input" placeholder="联系方式" > -->
            </div>
          </div>
        </div>

        <!-- 配送信息 -->
        <div class="info-group">
          <h3 class="section-title">配送信息</h3>
          <div class="form-row">
            <div class="form-item">
              <label class="label">
                <span class="required">*</span>送达日期:
              </label>
              <!-- <input type="date" class="input date-input" value="2025-09-25" v-model="orderDate"> -->
              <el-date-picker
                    v-model="sendTime"
                    type="datetime"
                    placeholder="选择送达时间"
                    format="YYYY.MM.DD HH:mm"
                    value-format="YYYY.MM.DD HH:mm"
                    class="edit-picker"
                  ></el-date-picker>
            </div>
            <!-- <div class="form-item">
              <label class="label">不限时间</label>
              <select class="select">
                <option>不限时间</option>
                <option>09:00-12:00</option>
                <option>12:00-15:00</option>
                <option>15:00-18:00</option>
                <option>18:00-21:00</option>
              </select>
            </div> -->
            <!-- <div class="form-item">
              <label class="label">配送方式</label>
              <select class="select">
                <option>市区免费配送</option>
                <option>郊区配送 +¥10</option>
                <option>加急配送 +¥20</option>
              </select>
            </div> -->
          </div>
        </div>

        <!-- 留言信息 -->
        <div class="info-group">
          <div class="form-row">
            <div class="form-item textarea-item">
              <label class="label">贺卡留言</label>
              <textarea class="textarea" placeholder="填写留言，最多可填写200字。" v-model="introduction"></textarea>
            </div>
            
          </div>
        </div>

        <!-- 发票信息 -->
        <div class="info-group">
          <div class="invoice-option">
            <input type="checkbox" id="invoice" class="invoice-checkbox">
            <label for="invoice" class="invoice-label">发票信息</label>
          </div>
        </div>
      </div>

      <!-- 核对购物清单 -->
      <div class="order-summary">
        <h3 class="section-title">核对购物清单</h3>

        <!-- 商品列表：使用v-for动态渲染多个商品 -->
        <div class="product-list">
          <!-- 检查是否有商品数量大于0 -->
          <template v-if="ccc.length>0">
            <!-- 使用v-for循环渲染每个商品 -->
            <div v-for="(item, index) in product" :key="item.flowerId" class="product-item">
              <!-- 商品图片：绑定item.image -->
              <img :src="item.image" :alt="item.name" class="product-img">
              <div class="product-info">
                <!-- 商品名称：绑定item.name -->
                <div class="product-name">{{ item.name }}</div>
                <!-- 商品数量 -->
                <div class="product-quantity">数量: X{{ ccc[index] }}</div>
              </div>
              <!-- 商品单价：绑定item.price -->
              <div class="product-price">店铺价: ¥{{ item.price }}</div>
            </div>
          </template>

          <!-- 空购物车提示（当所有商品数量都为0时显示） -->
          <div v-else class="empty-cart">
            您的购物车暂无商品，无法生成订单
          </div>
        </div>

        <!-- 订单金额信息：动态渲染计算后的金额 -->
        <div class="order-totals" v-if="ccc.length > 0">
          <!-- 商品总数和总金额：绑定product.quantity和orderAmount.totalGoodsPrice -->
          <div class="total-item">
            <span class="label">共{{ product.quantity }}件商品</span>
            <span class="value">总金额: ¥{{ orderAmount.totalGoodsPrice.toFixed(2) }}</span> <!-- toFixed(2)确保保留2位小数 -->
          </div>
          <!-- 配送费：绑定orderAmount.deliveryFee（后续可从后端获取） -->
          <div class="total-item">
            <span class="label">配送费:</span>
            <span class="value">¥{{ orderAmount.deliveryFee.toFixed(2) }}</span>
          </div>
          <!-- 优惠券折扣：绑定orderAmount.couponDiscount（后续可从后端获取） -->
          <div class="total-item">
            <span class="label">优惠券:</span>
            <span class="value">-¥{{ orderAmount.couponDiscount.toFixed(2) }}</span>
          </div>

          <!-- 支付方式（保留原逻辑） -->
          <div class="payment-method">
            <span class="label">支付方式:</span>
            <div class="payment-options">
              <label class="payment-option">
                <input type="radio" name="payment" checked>
                <i class="icon-wechat"></i>微信
              </label>
              <label class="payment-option">
                <input type="radio" name="payment">
                <i class="icon-alipay"></i>支付宝
              </label>
            </div>
          </div>

          <!-- 实付款：绑定orderAmount.finalPay（动态计算结果） -->
          <div class="final-total">
            <span class="label">实付款:</span>
            <span class="value">¥{{ orderAmount.finalPay.toFixed(2) }}</span>
          </div>

          <!-- 提交订单按钮（数量为0时禁用，避免无效提交） -->
          <button class="submit-btn" :disabled="ccc.length <= 0" @click="submitOrder">提交订单</button>
        </div>

      </div>
    </div>

    
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from '@/http/axios';
import { useLoginStore } from "@/stores/LoginStore";
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { el } from 'element-plus/es/locales.mjs';
const route = useRoute()

let userId = ref(route.params.userId)
// 订单留言
let introduction = ref('')
// 订单日期
var orderDate = ref('');

const product = reactive([
// {
//   flowerId: 1, // 商品ID前一个页面传的
//   name: '', // 商品名称
//   image: '', // 商品图片
//   price: 0, // 商品单价（
//   quantity: 0 // 商品数量
// }, {
//   flowerId: 5, // 商品ID前一个页面传的
//   name: '', // 商品名称
//   image: '', // 商品图片
//   price: 0, // 商品单价（
// }
]);
let ccc = reactive([0])// 商品数量

// 订单金额计算相关变量（基于商品数量和单价动态计算）
const orderAmount = reactive({
  totalGoodsPrice: 0, // 商品总价（单价 * 数量）
  deliveryFee: 0, // 配送费（可从后端配送规则接口获取，此处默认0）
  couponDiscount: 0, // 优惠券折扣（可从用户优惠券接口获取，此处默认0）
  finalPay: 0 // 实付款（商品总价 + 配送费 - 优惠券折扣）
});

const loginStore = useLoginStore();
let userInfo = reactive({
  data: {
    username: '',
    phone: '',
    address: ''
  }
})

import { useRouter } from 'vue-router';
const router = useRouter()

// 提交订单按钮
async function submitOrder(){
  console.log(ddd)
  console.log(introduction.value)
  console.log(sendTime.value)
  var data = {
    ids:ddd,
    'note':introduction.value,
    'sendTime':sendTime.value
  }
  var res = await axios.post('/cart/pay',data)
  if(res.data.code == 200){
    ElMessage.success('支付成功')
    router.push('/')
  }else{
    ElMessage.error(res.data.msg)
  }
}

var ddd = []

onMounted(async () => {
  ddd =route.params.flowerIds.split(',').map(Number)
  console.log(ddd)
  for(let i=0;i<ddd.length;i++){
    product.push({
      flowerId: ddd[i], 
      name: '', 
      image: '', 
      price: 0, 
    })
    console.log("===="+product[i].flowerId)
  }

  const userRes = await axios.get(`/userInfo/info`, {
    headers: { 'Authorization': loginStore.loginToken }
  });
  if(userRes.data.data.address == null){
    ElMessage.error("地址为空，请先填写地址")
    router.push('/userInfo')
  }
  Object.assign(userInfo.data, userRes.data.data); // 假设后端返回格式为 {data: {userId: 123, ...}}
  userId.value = userInfo.data.userId; // 将登录用户的userId赋值给userId变量

  let user_id = userId.value;
  
  for (let i = 0; i < product.length; i++) {
    let flower_id = product[i].flowerId;
    const res = await axios.get(`/cart/getcart/${user_id}/${flower_id}`, {
      headers: { 'Authorization': loginStore.loginToken } // 携带登录态，确保接口权限
    });
    ccc[i] = res.data || 0; // 若返回null，默认数量为0
  }

  for (let i = 0; i < product.length; i++) {
    let id = product[i].flowerId
    const res1 = await axios.get(`/flower/id/${id}`, {
      headers: { 'Authorization': loginStore.loginToken } // 携带登录态，确保接口权限
    });
    product[i].name = res1.data.data.name;
    product[i].price = res1.data.data.price;
    product[i].image = res1.data.data.image;
  }

  calculateOrderAmount();

})

const calculateOrderAmount = () => {
  // 1. 商品总价 = 单价 * 数量
  orderAmount.totalGoodsPrice = 0;
  for (let i = 0; i < product.length; i++) {
    orderAmount.totalGoodsPrice += product[i].price * ccc[i];
  }

  // 2. 实付款 = 商品总价 + 配送费 - 优惠券折扣（此处配送费和折扣暂默认0，可后续扩展）
  orderAmount.finalPay = orderAmount.totalGoodsPrice + orderAmount.deliveryFee - orderAmount.couponDiscount;

  // （可选）若数量为0，重置金额（避免显示0元订单）
  if (ccc.value === 0) {
    orderAmount.totalGoodsPrice = 0;
    orderAmount.finalPay = 0;
  }
};


// 表单数据
const formData = ref({
  consignee: {
    name: '',
    phone: '',
    address: ''
  },
  orderer: {
    name: '',
    phone: ''
  },
  delivery: {
    date: '2025-09-25',
    time: '不限时间',
    method: '市区免费配送'
  },
  messages: {
    card: '',
    buyer: ''
  },
  invoice: false,
  paymentMethod: 'wechat'
});

var sendTime = ref('')

// 当前选中的地址
const selectedAddress = ref(userInfo.address);

// 提交订单处理函数
const handleSubmit = () => {
  // 表单验证逻辑
  if (!formData.value.orderer.name || !formData.value.orderer.phone) {
    alert('请填写订购人信息');
    return;
  }

  // 提交订单的API调用逻辑
  console.log('提交订单数据:', formData.value);
  alert('订单提交成功！');
};
</script>

<style scoped>
/* 基础样式 */
.order-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  color: #333;
}

.section-title {
  background-color: #f0f0f0;
  padding: 10px 15px;
  margin: 0;
  font-size: 16px;
  font-weight: normal;
  color: #666;
  border-bottom: 1px solid #e0e0e0;
}

.info-group {
  border: 1px solid #e0e0e0;
  border-top: none;
  padding: 15px;
  margin-bottom: 20px;
}

.group-title {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #333;
  font-weight: normal;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 15px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  display: inline-block;
  width: 80px;
  text-align: right;
  margin-right: 10px;
  font-size: 14px;
}

.required {
  color: #ff4d4f;
  margin-right: 4px;
}

.input,
.select {
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  width: 250px;
  box-sizing: border-box;
}

.input:focus,
.select:focus,
.textarea:focus {
  outline: none;
  border-color: #4096ff;
  box-shadow: 0 0 0 2px rgba(64, 150, 255, 0.2);
}

.date-input {
  width: 150px;
}

.textarea-item {
  flex-direction: column;
  align-items: flex-start;
}

.textarea-item .label {
  margin-bottom: 8px;
}

.textarea {
  width: 300px;
  height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
  font-size: 14px;
  box-sizing: border-box;
}

/* 地址相关样式 */
.add-address {
  margin-bottom: 15px;
}

.add-btn {
  color: #4096ff;
  text-decoration: none;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
}

.icon-add {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 1px solid #4096ff;
  border-radius: 50%;
  text-align: center;
  line-height: 14px;
  margin-right: 5px;
  font-size: 12px;
}

.address-list {
  margin-bottom: 10px;
}

.address-card {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 10px;
  position: relative;
}

.address-card.selected {
  border-color: #4096ff;
  background-color: rgba(64, 150, 255, 0.05);
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.name {
  margin-right: 15px;
  font-weight: 500;
}

.phone {
  margin-right: 15px;
  color: #666;
}

.default-tag {
  background-color: #4096ff;
  color: white;
  font-size: 12px;
  padding: 2px 5px;
  border-radius: 3px;
}

.address-detail {
  color: #666;
  margin-bottom: 8px;
  line-height: 1.5;
}

.address-actions {
  text-align: right;
}

.address-actions a {
  color: #4096ff;
  text-decoration: none;
  font-size: 12px;
  margin-left: 15px;
}

/* 发票选项 */
.invoice-option {
  margin-top: 10px;
}

.invoice-checkbox {
  margin-right: 5px;
}

.invoice-label {
  font-size: 14px;
  cursor: pointer;
}

/* 订单摘要 */
.order-summary {
  border: 1px solid #e0e0e0;
}

.product-list {
  padding: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.product-info {
  flex: 1;
}

.product-name {
  margin-bottom: 5px;
  font-size: 14px;
}

.product-quantity {
  color: #666;
  font-size: 13px;
}

.product-price {
  color: #333;
  font-size: 14px;
}

/* 订单金额 */
.order-totals {
  padding: 15px;
}

.total-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.total-item .label {
  color: #666;
  width: auto;
}

/* 支付方式 */
.payment-method {
  display: flex;
  align-items: center;
  margin: 15px 0;
}

.payment-method .label {
  width: auto;
  margin-right: 15px;
}

.payment-options {
  display: flex;
  gap: 20px;
}

.payment-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.payment-option input {
  margin-right: 5px;
}

.icon-wechat,
.icon-alipay {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 5px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.icon-wechat {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%2307C160' d='M9.5 7.5c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm5 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-5 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm5 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z'/%3E%3C/svg%3E");
}

.icon-alipay {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%231677FF' d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1.41 16.09V20h-2.67v-1.93c-1.71-.36-3.16-1.46-3.27-3.4h1.96c.1 1.05.82 1.87 2.65 1.87 1.96 0 2.4-.98 2.4-1.59 0-.83-.44-1.61-2.67-2.14-2.48-.6-4.18-1.62-4.18-3.67 0-1.72 1.39-2.84 3.11-3.21V4h2.67v1.95c1.86.45 2.79 1.86 2.85 3.39H15.3c-.05-1.11-.64-1.87-2.33-1.87-1.5 0-2.4.68-2.4 1.64 0 .84.65 1.39 2.67 1.91s4.18 1.39 4.18 3.91c-.01 1.83-1.38 2.83-3.12 3.16z'/%3E%3C/svg%3E");
}

/* 实付款 */
.final-total {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
}

.final-total .label {
  font-size: 16px;
  color: #333;
}

.final-total .value {
  font-size: 18px;
  color: #ff4d4f;
  font-weight: bold;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  padding: 12px 0;
  background-color: #722ed1;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #531dab;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 0;
  }

  .form-item {
    width: 100%;
  }

  .input,
  .select,
  .textarea {
    width: 100%;
  }

  .textarea-item {
    width: 100%;
  }
}

/* 空购物车样式 */
.empty-cart {
  padding: 30px 0;
  text-align: center;
  color: #666;
  font-size: 14px;
  border-bottom: 1px solid #e0e0e0;
}

/* 禁用状态的提交按钮 */
.submit-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  transition: none;
}
</style>
